const LogModel = require('../../model/Log');
const moment = require('moment')
const Advertisement = require('../../model/Advertisement')

module.exports = {

    changeAdvertisement: async(req, res, next) => {
        if (req.body.id) {
            let advertisement = await Advertisement.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            advertisement.title = req.body.title,
                advertisement.image = req.body.image,
                advertisement.link = req.body.link,
                advertisement.date = req.body.date
            await advertisement.save()
            res.ok('修改成功')
        } else {
            let newAdvertisement = new Advertisement({
                title: req.body.title,
                image: req.body.image,
                link: req.body.link,
                isDelete: 0,
                date: req.body.date
            })
            await newAdvertisement.save()
            res.ok('创建成功')
        }
    },

    getOneAdvertisement: async(req, res, next) => {
        try {
            let advertisement = await Advertisement.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            return res.ok('查询广告成功', advertisement)
        } catch (e) {
            next(e)
        }
    },


    getAdvertisementList: async(req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            if (req.body.title) {
                option.title = new RegExp(req.body.title, 'i')
            }
            let count = await Advertisement.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let data = await Advertisement.find(option).skip((page - 1) * pageSize).limit(pageSize).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            return res.ok('获取列表成功', result)
        } catch (e) {
            next(e)
        }
    },

    deleteAdvertisement: async(req, res, next) => {
        try {
            let advertisement = await Advertisement.findOne({ _id: req.body.id }).exec()
            advertisement.isDelete = 1
            await advertisement.save()
            return res.ok('删除广告成功')
        } catch (e) {
            next(e)
        }
    },

};